"""Analyzer registry for language detection and routing."""

from __future__ import annotations

from pathlib import Path
from typing import Dict, List, Optional

from .base import LanguageAnalyzer
from .cpp_adapter import CppAnalyzerAdapter
from .fortran_adapter import FortranAnalyzerAdapter


class AnalyzerRegistry:
    """Registry of available language analyzers."""

    def __init__(self):
        self.analyzers: Dict[str, LanguageAnalyzer] = {}
        self._register_default_analyzers()

    def _register_default_analyzers(self):
        """Register the default analyzers."""
        try:
            self.analyzers["cpp"] = CppAnalyzerAdapter()
        except Exception:
            pass  # C++ analyzer not available

        try:
            self.analyzers["fortran"] = FortranAnalyzerAdapter()
        except Exception:
            pass  # Fortran analyzer not available

    def register_analyzer(self, name: str, analyzer: LanguageAnalyzer):
        """Register a custom analyzer."""
        self.analyzers[name] = analyzer

    def detect_language(self, path: Path) -> Optional[str]:
        """Detect the language of a file based on its extension."""
        extension = path.suffix.lower()

        for name, analyzer in self.analyzers.items():
            if extension in analyzer.get_supported_extensions():
                return name

        return None

    def get_analyzer(self, language: str) -> Optional[LanguageAnalyzer]:
        """Get analyzer for a specific language."""
        return self.analyzers.get(language)

    def analyze_paths(self, paths: List[Path], **kwargs) -> Dict[str, any]:
        """Analyze multiple paths, automatically detecting languages."""
        results = {}

        # Group paths by language
        language_paths: Dict[str, List[Path]] = {}

        for path in paths:
            if path.is_file():
                language = self.detect_language(path)
                if language:
                    if language not in language_paths:
                        language_paths[language] = []
                    language_paths[language].append(path)
            elif path.is_dir():
                # Collect all supported files in the directory
                for analyzer_name, analyzer in self.analyzers.items():
                    for ext in analyzer.get_supported_extensions():
                        pattern = f"**/*{ext}"
                        matching_files = list(path.glob(pattern))
                        if matching_files:
                            if analyzer_name not in language_paths:
                                language_paths[analyzer_name] = []
                            language_paths[analyzer_name].extend(matching_files)

        # Analyze each language group
        for language, lang_paths in language_paths.items():
            analyzer = self.get_analyzer(language)
            if analyzer:
                try:
                    result = analyzer.analyze(lang_paths, **kwargs)
                    results[language] = result
                except Exception as e:
                    print(f"Error analyzing {language} files: {e}")

        return results

    def get_available_languages(self) -> List[str]:
        """Get list of available language analyzers."""
        return list(self.analyzers.keys())


# Global registry instance
analyzer_registry = AnalyzerRegistry()